package com.bigfreakindeals.Activities;

import java.util.HashMap;

import com.bigfreakindeals.R;
import com.bigfreakindeals.Application.ApplicationEx;
import com.bigfreakindeals.Common.Constant;
import com.bigfreakindeals.Common.Tools;
import com.bigfreakindeals.Controller.AsynchListener;
import com.bigfreakindeals.Controller.ZipDownloader;
import com.bigfreakindeals.Models.ActiveDeal;
import com.bigfreakindeals.Models.DrawableImageSlug;
import com.bigfreakindeals.Models.UniversityDeals;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;

import android.widget.RelativeLayout;
import android.widget.TextView;


public class NoDealsActivity extends BaseActivity implements AsynchListener {
	
	RelativeLayout mainpage;
	RelativeLayout maindealsNoDeals; // grayed area no deals
	final Handler mHandler = new Handler();

	RelativeLayout terms;
	View header;

	Button headerButtonLeft;
	Button headerButtonRight;

	TextView headerTitle;
	Button btb_beanssays;

	LinearLayout headertopBG;
	LinearLayout headerbottomBG;
	
	TextView noDealsErrorMessage;
	
	ActiveDeal active = new ActiveDeal();
	
	UniversityDeals universitydeals;
	
	String errorMessage;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		//setup on school deals page
		
		setContentView(R.layout.nodeals);
		errorMessage = "No deals are currently active for your school.";
		updateLatestScreen();
		
		this.registerReceiver(activeDealsBRoadcastReceiver, new IntentFilter(Constant.EVENTS_UPDATESCREEN));

		mHandler.post(mImageGet);
	}

	private void updateUniversityTheme(boolean isDealPage) {
		
		if (universitydeals != null) {
			if (universitydeals.getSchoolTitle() != null) {
				
				headerTitle.setText(universitydeals.getSchoolTitle());
				headerTitle.setTextColor(universitydeals.color_school_font + (-16777216));
				
				headerTitle.setOnClickListener(this);
				headerTitle.setFocusable(true);
				headerTitle.setClickable(true);
				
			}
			
			if (universitydeals.color_school_bg > -1) {
				
				if (header!=null)
					header.setBackgroundColor(universitydeals.color_school_bg + (-16777216));
				ApplicationEx.getInstance().currentBG = universitydeals.color_school_bg + (-16777216);
				if (mainpage!=null)
					mainpage.setBackgroundColor(universitydeals.color_school_bg + (-16777216));
 
			}

				if (headerbottomBG!=null){
					headerbottomBG.setBackgroundColor(universitydeals.getColor_titleBarBottomColor() + (-16777216));
				}if (headertopBG!=null){
					headertopBG.setBackgroundColor((universitydeals.getColor_titleBarBottomColor() + 20) + (-16777216));
				}
				
			//TODO need o convert drawable to bitmap
		///	((ImageView)findViewById(R.id.beandog)).setBackgroundDrawable(universitydeals.drawablImages.bitmap_drawable_beansay_nodeal);
		if (universitydeals.drawablImages!=null && universitydeals.drawablImages.drawable_beansay_nodeal!=null)
			((ImageView)findViewById(R.id.beandog)).setBackgroundDrawable(universitydeals.drawablImages.drawable_beansay_nodeal);
		else 		
			((ImageView)findViewById(R.id.beandog)).setBackgroundDrawable(null);
		} // if university is not null
	}
	
	
	private void callBeansSaysActivity() {

		Intent i = new Intent(this, BeansSaysActivity.class);
		View view = ActiveDealsActivityGroup.activedealsgroup.getLocalActivityManager()
				.startActivity("BeansSay", i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)).getDecorView();

		// Again, replace the view
		ActiveDealsActivityGroup.activedealsgroup.replaceView(view);
	}

	@Override
	public void onClick(View v) {
		if (v == headerButtonLeft){//schools
			ApplicationEx.getInstance().controller.current = this;
			Intent getSchoolIntent = new Intent(this, GetSchoolAllActivity.class);
			startActivity(getSchoolIntent);
		} else if (v == btb_beanssays){
			callBeansSaysActivity();
		}
	}
	 // Create runnable for posting
    final Runnable mImageGet = new Runnable() {
        public void run() {
        	Log.i("NODEALSACTIVITY","UPDSTE DRAWABLE");

        	updateDrawable();
			
        }
    };
    
    public void downloadImage(final String slug){
			String PATH = "http://unimiser.com/img/slugimages/android/large/"+slug+".zip";
				try{
				ZipDownloader zip = new ZipDownloader();
				zip.listener =this;
				zip.execute(new String[]{PATH,slug});

			}catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}
	

}
  public DrawableImageSlug getDrawableImage(String slug){
	  DrawableImageSlug result=null;
	  Log.e("DrawableImageSlug",slug);
	  	
	  if (ApplicationEx.getInstance().drawableImages == null )
		  ApplicationEx.getInstance().drawableImages = new HashMap<String, DrawableImageSlug>();
	  
	  
	  if (ApplicationEx.getInstance().drawableImages.size() == 0)//download images
	  {
		  Log.e("DrawableImageSlug","size is zero downoad the images");
			 
		  downloadImage(slug);
		 
	  }
	  
	  if (!ApplicationEx.getInstance().drawableImages.containsKey(slug)) //download images
	  {
		  Log.e("DrawableImageSlug",ApplicationEx.getInstance().drawableImages+" "+slug);
			
		  downloadImage(slug);
		
	  }  
	   result = (ApplicationEx.getInstance().drawableImages).get(slug);
	  return result;
  }
    private void updateDrawable(){
    	if (ApplicationEx.getInstance().myProfile.getlastSelectedSchool().drawablImages == null)
    		ApplicationEx.getInstance().myProfile.getlastSelectedSchool().drawablImages = new DrawableImageSlug(ApplicationEx.getInstance().myProfile.getlastSelectedSchool().getImageSlug());
    	
    	//check db if slug exist
    	//else download it
    	ApplicationEx.getInstance().myProfile.getlastSelectedSchool().drawablImages = getDrawableImage(ApplicationEx.getInstance().myProfile.getlastSelectedSchool().getImageSlug());
    	
    		
    		
    	
    }
	
	@Override
	public void onResume() {
		super.onResume();
		
		System.out.print("onresume");
		
	
	}
	@Override
	public void onDestroy() {
		super.onDestroy();
		this.unregisterReceiver(activeDealsBRoadcastReceiver);

	}
	// Create runnable for posting
    final Runnable mImageDisplay = new Runnable() {
        public void run() {
        	updateLatestScreen();
        	
        }
    };
    private void updateLatestScreen(){
    	
    	universitydeals =  ApplicationEx.getInstance().myProfile.getlastSelectedSchool();
    	
    	universitydeals.drawablImages = ApplicationEx.getInstance().drawableImages.get(universitydeals.getImageSlug());
    	
    	Log.i("NOACTIVITDEALS"," "+ universitydeals.getImageSlug()+" "+universitydeals.drawablImages);
    	
		header = (View) findViewById(R.id.header);

		headerButtonLeft = (Button) findViewById(R.id.header_iconleft);
		
		headerButtonRight = (Button) findViewById(R.id.header_iconright);
		
		headerButtonRight.setBackgroundResource(R.drawable.btn_deals_unselected);

		headerbottomBG = (LinearLayout) findViewById(R.id.headerbg_bottom);

		headertopBG = (LinearLayout) findViewById(R.id.headerbg_top);
		headerTitle = (TextView) findViewById(R.id.header_title);
		headerTitle.setOnClickListener(this);
		headerTitle.setFocusable(true);
		headerTitle.setClickable(true);
		headerButtonLeft.setOnClickListener(this);
		
		maindealsNoDeals = (RelativeLayout) findViewById(R.id.noactivedealsmessage);
		Drawable drawable = new GradientDrawable(GradientDrawable.Orientation.TOP_BOTTOM , new int[]{0xfff2f2f2,0xffC2C2C2});
		int stroke = 1;/*stroke width*/
		
		((GradientDrawable)drawable).setCornerRadii(new float[] {0,0,0,0,10,10,10,10});
		((GradientDrawable)drawable).setStroke(stroke, 0xffC2C2C2);
		
		
		maindealsNoDeals.setBackgroundDrawable(drawable);
		
		findViewById(R.id.separator_top).setBackgroundDrawable(Tools.getDrawableButtonGeneric(new int[]{universitydeals.color_school_bg+(-16777216), 0xffB8b8b8}, 0,GradientDrawable.Orientation.TOP_BOTTOM));
		
		mainpage = (RelativeLayout) findViewById(R.id.activedealsmain);
		mainpage.setBackgroundColor(universitydeals.color_school_bg + (-16777216));
		
		noDealsErrorMessage = (TextView) findViewById(R.id.nodealserrormessage);
		noDealsErrorMessage.setTextColor(universitydeals.color_school_bg + (-16777216));
		noDealsErrorMessage.setText(errorMessage);
		btb_beanssays  = (Button) findViewById(R.id.button_beansays);
		
		btb_beanssays.setOnClickListener(this);
		//update colors & bg based on university theme
		updateUniversityTheme(false);
    }

	@Override
	public void updateScreen(boolean toUpdate) {
		// TODO Auto-generated method stub
		mHandler.post(mImageDisplay);
		
	}

	public BroadcastReceiver activeDealsBRoadcastReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			Log.i("onreceive","no deals 1"+intent.getAction());
			
			if (intent.getAction().equals(Constant.EVENTS_UPDATESCREEN)) {
				updateScreen(true);
			}
			}
	};


}
